package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import com.atguigu.gmall.product.model.BaseAttrInfo;
import com.atguigu.gmall.product.model.BaseAttrValue;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class BaseAttrInfoServiceImpl  extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrInfoService {


    @Autowired
    private BaseAttrValueService baseAttrValueService;

    /**
     * 根据1,2,3级分类ID查询分类下包含平台属性，以及平台属性值
     *
     * @param category1Id
     * @param category2Id
     * @param category3Id
     * @return
     */
    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //1.方式一：LambdaQueryWrapper动态拼接条件 查询 指定分类下包含平台属性列表  再遍历列表再次查询该属性下平台属性值
        //2.方式二：编写动态SQL完成 一对多 配置
        return baseMapper.getAttrInfoList(category1Id, category2Id, category3Id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId() == null){
            this.save(baseAttrInfo);
            this.saveBatchAttrValue(baseAttrInfo.getId(), baseAttrInfo.getAttrValueList());
        }else {
            this.updateById(baseAttrInfo);
            LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BaseAttrValue::getAttrId, baseAttrInfo.getId());
            baseAttrValueService.remove(queryWrapper);

            this.saveBatchAttrValue(baseAttrInfo.getId(), baseAttrInfo.getAttrValueList());

        }
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        LambdaQueryWrapper<BaseAttrValue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseAttrValue::getAttrId, attrId);
        return baseAttrValueService.list(queryWrapper);

    }

    private void saveBatchAttrValue(Long id, List<BaseAttrValue> attrValueList) {

        if (!CollectionUtils.isEmpty(attrValueList)){
            attrValueList.forEach(baseAttrValue -> baseAttrValue.setAttrId(id));
            baseAttrValueService.saveBatch(attrValueList);
        }
    }


}